package org.objectrproject.web.beans;

import java.util.List;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import org.objectrproject.basic.Class;
import org.objectrproject.service.GenericService;

import com.icesoft.faces.component.tree.IceUserObject;

/**
 * <p>
 * A basic backing bean for a ice:tree component.  The only instance variable
 * needed is a DefaultTreeModel Object which is bound to the icefaces tree
 * component in the jspx code.</p>
 * <p>
 * The tree created by this backing bean is very simple, containing only text
 * nodes.  The plus and minus icons which expand the tree are rendered because
 * of attributes set at the component level.
 * </p>
 *
 */
public class TreeBean {

    // tree default model, used as a value for the tree component
    private DefaultTreeModel model; 

    public TreeBean(GenericService<Class> classService){

    	// create root node with its children expanded
        DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
        IceUserObject rootObject = new IceUserObject(rootTreeNode);
        rootObject.setText("Root");
        rootObject.setExpanded(true);
        rootTreeNode.setUserObject(rootObject);

        // add branch node for classes     
        DefaultMutableTreeNode nodeClasses = new DefaultMutableTreeNode();
        IceUserObject iuoClasses = new IceUserObject(nodeClasses);
        iuoClasses.setText("Classes");
        nodeClasses.setUserObject(iuoClasses);
        //branchObjectClasses.setLeaf(true);
        rootTreeNode.add(nodeClasses);
        
        // add classes        
    	List<Class> classes = classService.getObjects();
    	
    	for (Class c : classes) {
        	DefaultMutableTreeNode classNode = new DefaultMutableTreeNode();
            IceUserObject classObject = new IceUserObject(classNode);
            classObject.setText(c.toString());
            classNode.setUserObject(classObject);
            classObject.setLeaf(true);
            nodeClasses.add(classNode);
        }
        
 
    	// model is accessed by by the ice:tree component
        model =  new DefaultTreeModel(rootTreeNode);
    }

    /**
     * Gets the tree's default model.
     *
     * @return tree model.
     */
    public DefaultTreeModel getModel() {    	
        return model;
    }
}

